import { GlobalContainer } from '@/RoomDesign/common/GlobalContainer'
import type { RoomObject } from '@/RoomDesign/domain/entity/share/RoomObject'
import { MeshBuilderManager } from '@/RoomDesign/infrastructure/three-render/build/MeshBuilderManager'
import type { RoomGroup } from '@/RoomDesign/infrastructure/three-render/entity/RoomGroup'
import type { ThreeRender3DController } from '@/RoomDesign/infrastructure/three-render/ThreeRender3DController'
import type { ThreeSceneController } from '@/RoomDesign/infrastructure/three-render/ThreeSceneController'

export class ThreeRenderService {
  private static _instance: ThreeRenderService

  // 依赖
  private _meshBuilderManager: MeshBuilderManager = GlobalContainer.meshBuilderManager
  private _threeSceneController: ThreeSceneController = GlobalContainer.threeSceneController
  private _threeRender3DController: ThreeRender3DController =
    GlobalContainer.threeRender3DController

  public static getInstance(): ThreeRenderService {
    if (!ThreeRenderService._instance) {
      ThreeRenderService._instance = new ThreeRenderService()
    }
    return ThreeRenderService._instance
  }
  private constructor() {}

  /** 初始化initViewport3D
   * @param canvasContainer
   */
  public initViewport3D(canvasContainer: HTMLDivElement) {
    // 这里获取offsetWidth必须该dom是可见的，也就是加入到dom树中的

    this._threeSceneController.init()
    this._threeRender3DController.init(this._threeSceneController, canvasContainer)
    this._threeRender3DController.startRender()
  }

  public createMesh(entity: RoomObject): RoomGroup {
    return this._meshBuilderManager.buildEntityMesh(entity)
  }

  public createMeshAndAddToScene(entity: RoomObject): void {
    const houseGroup = this.createMesh(entity)
    this.addToScene(houseGroup)
  }

  public addToScene(houseGroup: RoomGroup): void {
    this._threeSceneController.addToScene(houseGroup)
  }
}
